package org.facyt.vacas.view.login;

import javax.servlet.http.HttpSession;

import org.facyt.commons.util.VaadinUtil;
import org.facyt.commons.view.interfaces.IWindow;
import org.facyt.vacas.util.ConstantesWeb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Component;

import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;

@Component("login")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoginPanel extends Window implements IWindow {

	private static final long serialVersionUID = 3516303139129648606L;

	protected final Logger logger = LoggerFactory.getLogger(LoginPanel.class);

	private static final String TITLE_PANEL_LOGIN = "title-login";
	private static final String USERNAME_LABEL_LOGIN = "label-username-login";
	private static final String PASSWORD_LABEL_LOGIN = "label-password-login";
	private static final String BOTON_LABEL_LOGIN = "label-boton-login";

	public LoginPanel() {
		super();
		init();
	}

	protected void init() {
		setCaption(VaadinUtil.getProperties(ConstantesWeb.FacytApplication.TITULO_PAGINA));
		try {
			CustomLayout loginLayout = new CustomLayout(
					LoginPanel.class
							.getResourceAsStream("/template/login.html"));

			Label titleLabel = new Label();
			titleLabel.setValue(VaadinUtil
					.getProperties(ConstantesWeb.LoginMessages.LOGIN_TITULO));
			loginLayout.addComponent(titleLabel, TITLE_PANEL_LOGIN);

			Label usuarioLabel = new Label();
			usuarioLabel
					.setValue(VaadinUtil
							.getProperties(ConstantesWeb.LoginMessages.LOGIN_USUARIO_LABEL));
			loginLayout.addComponent(usuarioLabel, USERNAME_LABEL_LOGIN);

			Label contraseniaLabel = new Label();
			contraseniaLabel
					.setValue(VaadinUtil
							.getProperties(ConstantesWeb.LoginMessages.LOGIN_CONTRASENIA_LABEL));
			loginLayout.addComponent(contraseniaLabel, PASSWORD_LABEL_LOGIN);

			Label botonLabel = new Label();
			botonLabel
					.setValue(VaadinUtil
							.getProperties(ConstantesWeb.LoginMessages.LOGIN_BOTON_LABEL));
			
			loginLayout.addComponent(botonLabel, BOTON_LABEL_LOGIN);
			loginLayout.setSizeFull();
			addComponent(loginLayout);
			setSizeFull();
			
			//se obtien la sesion
			
			HttpSession session = VaadinUtil.getSession();
			
			Exception exception = (Exception) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
			
			if (exception != null) {
				session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
				VaadinUtil.showMessageError("login.error.label");
			}
			
		} catch (Exception e) {
			logger.error("ERROR", e);
		}
	}
	
}
